import { Point } from "./common";

export function getIntersectionPoints(points1: Point[], points2: Point[]): Point[] {
    const intersections: Point[] = [];

    for (let i = 0; i < points1.length - 1; i++) {
        const p1 = points1[i];
        const p2 = points1[i + 1];

        for (let j = 0; j < points2.length - 1; j++) {
            const p3 = points2[j];
            const p4 = points2[j + 1];

            const denominator =
                (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);

            if (denominator === 0) {
                // lines are parallel
                continue;
            }

            const ua =
                ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) /
                denominator;
            const ub =
                ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) /
                denominator;

            if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
                const x = p1.x + ua * (p2.x - p1.x);
                const y = p1.y + ua * (p2.y - p1.y);
                intersections.push({ x, y });
            }
        }
    }

    return intersections;
}
